package com.lu.security.cipher;

import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.lu.security.key.DefaultKey;
import com.lu.security.tools.HexTools;

/**
 * author: luqihua
 * date:2021/12/20
 * description: AES加密工具类
 * 加密模式是 CBC
 * 数据块分组 PKCS5Padding
 **/
public class AESCipher {
    private static final String ALGORITHM_CBC = "AES/CBC/PKCS5Padding";

    private final Key mSecretKeySpec;
    private final AlgorithmParameterSpec mIvParameterSpec;

    public AESCipher(String keyText64, String iVText64) {
        this(HexTools.decodeFromBase64(keyText64), HexTools.decodeFromBase64(iVText64));
    }


    public AESCipher(byte[] keyBytes, byte[] ivBytes) {
        mSecretKeySpec = new SecretKeySpec(keyBytes, "AES");
        mIvParameterSpec = new IvParameterSpec(ivBytes);
    }


    public static AESCipher getDefault() {
        return new AESCipher(DefaultKey.nDefaultKey(), DefaultKey.nDefaultIV());
    }

    public String encryptBase64(String text) throws GeneralSecurityException {
        //指定使用AES加密
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);

        cipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mIvParameterSpec);

        byte[] bytes = cipher.doFinal(text.getBytes());

        return HexTools.encodeToBase64(bytes);
    }

    public String decryptBase64(String encodeString) throws GeneralSecurityException {
        //指定使用AES加密
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
        cipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);

        byte[] src = HexTools.decodeFromBase64(encodeString);
        byte[] bytes = cipher.doFinal(src);
        return new String(bytes);
    }

    public byte[] encrypt(byte[] data) throws GeneralSecurityException {
        //指定使用AES加密
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);

        cipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
        return cipher.doFinal(data);
    }

    public byte[] decrypt(byte[] encryptData) throws GeneralSecurityException {
        //指定使用AES加密
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
        cipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
        return cipher.doFinal(encryptData);
    }
}
